package job2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock
 */
public class Main7 {

    private static volatile int result;

    private static final ReentrantLock lock = new ReentrantLock();

    private static final Condition condtion =  lock.newCondition();

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法
        Thread thread = new Thread(() -> {
            lock.lock();
            try {
                result = sum();
                //唤醒主线程
                condtion.signal();
            }catch (Exception e){
            }finally {
                if(lock.isLocked()){
                    lock.unlock();
                }
            }
        });

        lock.lock();
        try {
            thread.start();
            //主线程阻塞
            condtion.await();
        }catch (Exception e){
        }finally {
            if(lock.isLocked()){
                lock.unlock();
            }
        }

        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + result);
        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");
    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }

}
